package com.lovezy.platform.core.base.query;

import com.github.pagehelper.ISelect;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import java.util.Optional;

/**
 * 使用pagehelper的基类
 * Created by jin on 2017/11/5.
 */
public class Pager {

    public static <E> Page<E> doPage(BaseQuery query, ISelect select) {
        return PageHelper.startPage(query.getPage(), query.getPageSize()).pageSizeZero(true).doSelectPage(select);
    }

    public static <E> PageInfo<E> doPageInfo(BaseQuery query, ISelect select) {
        return PageHelper.startPage(query.getPage(), query.getPageSize()).pageSizeZero(true).doSelectPageInfo(select);
    }

    public static <E> Page<E> doPageAll(ISelect select) {
        return PageHelper.startPage(1,0).pageSizeZero(true).doSelectPage(select);
    }

    public static <E> PageInfo<E> doPageInfoAll(ISelect select) {
        return PageHelper.startPage(1, 0).pageSizeZero(true).doSelectPageInfo(select);
    }

    public static <E> Optional<E> doSingleton(ISelect select) {
        return Optional.ofNullable(doSingletonNullAble(select));
    }

    public static <E>E doSingletonNullAble(ISelect select) {
        Page<E> page = PageHelper.startPage(1, 1).doSelectPage(select);
        if (!page.isEmpty()) {
            return page.get(0);
        }
        return null;
    }
}
